package com.geekchique.runningbuddy.model;

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;

import android.location.Location;
import android.net.ParseException;

import com.geekchique.runningbuddy.activity.stopwatch.StopwatchTools;

public class ListOfJogs extends LinkedList<Jog>{

	@Override
	public void clear() {
		totalJoggingTime = 0L;
		result = "";
		super.clear();
	}

	private static final long serialVersionUID = 23232L;
	private long totalJoggingTime = 0L;
	private SimpleDateFormat showingDateFormatter;
	GregorianCalendar totalTime;
	String result ="";

	public boolean add(Jog jog) {
		long timeToAdd = StopwatchTools.getDiffMilli(jog.getStartTime(), jog.getStopTime());
		totalJoggingTime = totalJoggingTime + timeToAdd;

		return super.add(jog);
	}

	public String getTotalJoggingTime() {
		totalTime = new GregorianCalendar();
		totalTime.setTimeInMillis(totalJoggingTime);

		if(totalTime.get(Calendar.HOUR) > 0) {
			totalTime.set(Calendar.HOUR, totalTime.get(Calendar.HOUR) -1);
		}

		showingDateFormatter = new SimpleDateFormat("HH:mm:ss:SS");

		try{
			result = new String(showingDateFormatter.format(totalTime.getTime()));

	    	}catch(ParseException e){
	    		System.out.println("Totalling the date failed");
	    		e.printStackTrace();
	    	}

		return result;
	}

	@Override
	public String[][] toArray() {
		int size = super.size();
		int jogNo = 0;
		String[][] arrayOfJogs = new String[size][];
		StringBuffer coOrdinates;
		Iterator<Jog> i = super.listIterator();
		DecimalFormat myFormatter = new DecimalFormat("0.000000");



		while (i.hasNext()) {
			Jog jog = (Jog) i.next();
			String curr[] = new String[2];
			Map<Long, Location> loc = jog.getlocationsAndTimes();
			coOrdinates = new StringBuffer();

			curr[0] = new String (jog.name);
			int noOfLocations = loc.entrySet().size();
			int curentLoc = 0;

			for(Entry<Long, Location> location : loc.entrySet()){
				if (curentLoc == noOfLocations -1){
					coOrdinates.append(  myFormatter.format((location.getValue().getLongitude() / 1000000))  + "," + myFormatter.format((location.getValue().getLatitude()/ 1000000)) );
				}else{
					coOrdinates.append( myFormatter.format((location.getValue().getLongitude() / 1000000)) + "," + myFormatter.format((location.getValue().getLatitude()/ 1000000)) + ",");
				}
				curentLoc++;
			}

			curr[1] = new String (coOrdinates);

			arrayOfJogs[jogNo] = curr;
			jogNo++;
		}

		return arrayOfJogs;
	}

	
	
}

